<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\RolePermission;
class Role extends Model
{
    protected $table='role';
    protected $guarded=[];
    public $timestamps=false;

    /*
     * 角色权限表关联关系
     * */
    public function permissions()
    {
        return $this->belongsToMany('App\Models\Permission','role_permission','role_id','permission_id');
    }

    //保存新建用户
    public static function checkRole($request){
        $data['rolename']=$request->rolename;
        $newRole=Role::create($data);
        if($newRole){
            return redirect()->back()->with('status','小主！添加成功！');
        }else{
            $request->session()->flash('rolename', "$request->rolename");
            return redirect()->back()->with('status','小主！添加失败!');
        }

    }

    /*
    * 编辑用户
    * */
    public static function updateRole($request){
        $data['rolename']=$request->rolename;
        $updateRole=Role::where('id',$request->roleId)->update($data);
        if($updateRole){
            return  back()->with('status','修改成功');
        }else{
            return  back()->with('status','房源信息未做任何修改');
        }
    }

    //保存添加权限
    public static function checkPermission($request){
         $permissionArr=array_keys($request->permissions);
         $num=count($permissionArr);
         for($i=0;$i<$num;$i++){
             $data['permission_id']=$permissionArr["$i"];
             $data['role_id']=$request->roleId;
             RolePermission::firstOrCreate($data);
         }
        return redirect()->back()->with('status','小主！添加成功！');

    }

}
